package com.Servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.Server.UserList;
import com.Server.UserTrace;

@SuppressWarnings("serial")
public class UserListServlet extends HttpServlet {

	String getCookie(Cookie[] cookies, String key) {
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(key))
					return cookie.getValue();
			}
		}
		return null;
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();

		String username = new String(getCookie(request.getCookies(), "name").getBytes("ISO-8859-1"), "UTF-8");

		if (session.getAttribute(username) == null && !username.isEmpty()) {
			UserTrace ut = new UserTrace();
			ut.setUser(username);
			session.setAttribute(username, ut);
			UserList.addUser(ut.getUser());
			session.setMaxInactiveInterval(300);
		}

		Vector<String> vector = UserList.getList();
		if (vector != null && vector.size() > 0) {
			out.println("UserList");
			for (int i = 0; i < vector.size(); i++) {
				out.println(vector.elementAt(i));
			}
		}
		out.flush();
		out.close();
	}

}
